package alogrithm;

/**
 * @author lbw
 * @version 1.0
 * @date 2021/10/18 9:00
 */
public class ReverseKGroup {

    class ListNode {
        int val;
        ListNode next = null;
    }

    public ListNode reverseKGroup(ListNode head, int k) {
        // write code here
        if (head == null || head.next == null || k == 1) {
            return head;
        }
        int n = 0;
        ListNode dummyNode = new ListNode();
        dummyNode.next = head;
        ListNode pre = dummyNode;
        ListNode curr = head;
        ListNode next = null;
        while (head != null) {
            n++;
            head = head.next;
        }
        for (int i = 0; i < n / k; ++i) {
            for (int j = 0; j < k; ++j) {
                next = curr.next;// 保存curr的下一个结点
                curr.next = next.next;
                next.next = pre.next;
                pre.next = next;
            }
            pre = curr;
            curr = next;
        }
        return dummyNode.next;
    }
}
